# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:
import os
from base_class import BaseClass

class CreateImgFolder(BaseClass):

    def __init__(self, **kwargs):
        self.db_config = kwargs.get("db_config")
        self.conn, self.curs = self.get_conn_curs(db_config=self.db_config, type='dict')
        self.old_img_path = '/Users/duanmengdi/Documents/nissan_new/nissan_all_img/'
        self.img_base_path = '/Users/duanmengdi/Documents/nissan_new/nissan_img/'

    def get_cmi_dict(self):
        sql = '''select distinct `cid`,`mid`,`imgName` from `cars_structure_collection` where `brandCode`="nissan"'''
        self.curs.execute(sql)
        data = self.curs.fetchall()
        _dict = {i.get("cid"):[] for i in data}
        for i in data:
            cid = i.get("cid")
            d = {"mid":i.get("mid"), 'imgName':i.get("imgName")}
            if cid not in _dict:
                continue
            _dict[cid].append(d)
        return _dict

    def run(self):
        # 获取分组表中所有cid对照的图片名字典
        cmi_dict = self.get_cmi_dict()
        # {cid:[{'mid':mid, 'img':img},{...},{}...], cid:[{}...]}
        # 遍历每个cid,获取其对应的mid,img字典
        fd = open('./no_img2.txt', 'w')
        for cid in cmi_dict:
            cid = cid

            mid_img_list = cmi_dict[cid]
            # 创建cid命名的文件夹
            cid_path = self.img_base_path+str(cid)
            if not os.path.exists(cid_path):
                os.mkdir(cid_path)
            for mid_img_dict in mid_img_list:
                mid = mid_img_dict.get("mid").replace(' ','')
                imgName = mid_img_dict.get("imgName")
                src_path = self.old_img_path+imgName+'.png'
                dest_path = cid_path+'/'+mid+'.png'
                if not os.path.exists(src_path):
                    imgName = imgName.replace('*',"Z")
                    src_path = self.old_img_path + imgName + '.png'
                    if not os.path.exists(src_path):
                        fd.write(mid)
                        fd.write('\n')
            #     cp_command = 'cp {} {}'.format(src_path, dest_path)
            #     try:
            #         os.system(cp_command)
            #     except:
            #         continue
            #     # print(cp_command)
            # print("{}创建完毕".format(cid))
        fd.close()

        # 遍历字典列表
        # 获取mid,img
        # 初始路径以img.png命名,新文件以mid.png命名


if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8"
    )
    tools = CreateImgFolder(db_config=db_config)
    tools.run()
